# 用于UDP数据传输

import binascii
import socket

conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recv_addr = ("", 1399)
conn.bind(recv_addr)
conn.settimeout(1)  # 设置超时时间

# 设置允许广播
conn.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)


def get_send_str():
    ip_address = socket.gethostbyname(socket.gethostname())
    return ("WIT" + ip_address + "\r\n").encode()


def send_broadcast_for_sensor():
    all_addr = ("255.255.255.255", 9250)
    send_data = get_send_str()
    conn.sendto(send_data, all_addr)


def get_sensor_raw_data():
    try:
        recv_data = conn.recvfrom(1024)
        data_str = binascii.b2a_hex(recv_data[0]).decode('utf-8')
        return data_str
    except socket.timeout:
        return None
